﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace ButtonTree2
{
    public class TwoLineText : ILineText
    {
        public TwoLineText()
        {
            _strFmtLine1 = new StringFormat();
            _strFmtLine1.Alignment = StringAlignment.Center;
            _strFmtLine1.LineAlignment = StringAlignment.Near;
            _strFmtLine1.FormatFlags = StringFormatFlags.NoWrap;

            _strFmtLine2 = new StringFormat();
            _strFmtLine2.Alignment = StringAlignment.Center;
            _strFmtLine2.LineAlignment = StringAlignment.Far;
            _strFmtLine2.FormatFlags = StringFormatFlags.NoWrap;
        }

        public const int ROW_GAP = 0;   // 文字行间距

        private Size _size;

        private string _text;
        private string _line1;
        private string _line2;

        private StringFormat _strFmtLine1;
        private StringFormat _strFmtLine2;

        private bool _bTextChanged = false;

        public string Text
        {
            get
            {
                return _text;
            }
            set
            {
                if (_text != value)
                {
                    _text = value;
                    _bTextChanged = true;
                }
            }
        }

        public string Line1
        {
            get
            {
                return _line1;
            }
        }

        public string Line2
        {
            get
            {
                return _line2;
            }
        }



        // 获取合适的大小
        public Size GetHintSize(/*Graphics g, Font font*/)
        {
            /*UpdateTextSize(g, font);*/
            return _size;
        }

        // 更新双行文本的宽高，在调用GetHintSize前应调用此函数
        public void UpdateTextSize(Graphics g, Font font)
        {
            if (_bTextChanged)
            {
                // 若文字改变，需要计算一遍Size
                SeparateTextToTowLine(g, font);
                _bTextChanged = false;
            }
        }

        // 绘制
        public void Draw(Graphics g, Font font, Brush brush, Rectangle rect)
        {
            UpdateTextSize(g, font);

            int left = rect.Left + (rect.Width - _size.Width) / 2;
            int top = rect.Top + (rect.Height - _size.Height) / 2;

            Rectangle rectCenterText = new Rectangle(left, top, _size.Width, _size.Height);

            //g.DrawRectangle(Pens.Blue, rectCenterText);

            g.DrawString(_line1, font, brush, rectCenterText, _strFmtLine1);

            if (!String.IsNullOrEmpty(_line2))
            {
                g.DrawString(_line2, font, brush, rectCenterText, _strFmtLine2);
            }

        }

        // 已经设置了 line1 和 line2文字，计算出总大小
        private void CalcTowLineSize(Graphics g, Font font)
        {
            float width = 0f;
            float height = 0f;

            height = ROW_GAP; // 文字行间距

            string[] lines = new string[] { _line1, _line2 };

            // 计算每行文字Size
            for (int i = 0; i < 2; ++i)
            {
                SizeF sizeF = g.MeasureString(lines[i], font);
                height += sizeF.Height;

                width = Math.Max(width, sizeF.Width);
            }

            _size.Width = (int)width + 1;
            _size.Height = (int)height + 1;
        }

        private void SeparateTextToTowLine(Graphics g, Font font)
        {
            if (String.IsNullOrEmpty(_text))
            {
                _line1 = String.Empty;
                _line2 = String.Empty;
                _size.Width = 0;
                _size.Height = 0;
                return;
            }

            // 情况1：字符数量少于5，或者宽度少于一定数值，则只作为一行
            {
                SizeF sizeF = g.MeasureString(_text, font);

                if (_text.Length <= 4 || sizeF.Width <= 60)
                {
                    _line1 = _text;
                    _line2 = String.Empty;

                    _size.Width = (int)sizeF.Width + 1;
                    _size.Height = (int)sizeF.Height + 1;
                    return;
                }
            }

            // 情况2：非分隔符分隔成两行，则直接拆分为两行
            {
                string[] subStrs = _text.Split(' ', '\n', '\t');
                if (subStrs.Length == 2)
                {
                    // 分成两行

                    _line1 = subStrs[0];
                    _line2 = subStrs[1];
                    CalcTowLineSize(g, font);
                    return;
                }
            }

            // 情况3： 适用于多个英文单词 拆分为两行
            {
                string[] subStrs = _text.Split(' ', '\n', '\t');

                if (subStrs.Length > 2)
                {
                    float[] arrSubStrWidth = new float[subStrs.Length]; // 存储每一个字字符串的宽度
                    float sumWidth = 0f;    // 存储宽度总和，对于空格的宽度忽略不计

                    for(int i = 0; i < subStrs.Length; ++i)
                    {
                        arrSubStrWidth[i] = g.MeasureString(subStrs[i], font).Width;
                        sumWidth += arrSubStrWidth[i];
                    }

                    float accumulationWidth = 0f;   // 累加宽度
                    int lineOneCount = 1;
                    for (int i = 0; i < subStrs.Length; ++i)
                    {
                        accumulationWidth += arrSubStrWidth[i];
                        if (accumulationWidth >= sumWidth / 2)
                        {
                            lineOneCount = i + 1;
                            break;
                        }
                    }

                    // 防止最后一段宽度过长，超过总宽度50%，结果导致分配到了第一行，第二行为空
                    if (lineOneCount == subStrs.Length)
                    {
                        lineOneCount -= 1;
                    }

                    _line1 = String.Join(" ", subStrs, 0, lineOneCount);
                    _line2 = String.Join(" ", subStrs, lineOneCount, subStrs.Length - lineOneCount);
                    CalcTowLineSize(g, font);
                    return;
                }
            }

            // 情况4： 适用于长串且无空格的中文和英文字母
            {
                // 获取总宽度
                float totalWidth = g.MeasureString(_text, font).Width;

                StringBuilder strBuilder = new StringBuilder();
                string subStr = String.Empty;
                int lineOneCharCount = 1;

                for (int i = 0; i < _text.Length; ++i)
                {
                    strBuilder.Append(_text[i]);
                    subStr = strBuilder.ToString();

                    if (g.MeasureString(subStr, font).Width > totalWidth / 2)
                    {
                        lineOneCharCount = i + 1;
                        break;
                    }
                }

                _line1 = _text.Substring(0, lineOneCharCount);

                if (lineOneCharCount < _text.Length)
                {
                    _line2 = _text.Substring(lineOneCharCount, _text.Length - lineOneCharCount);
                }

                CalcTowLineSize(g, font);
                return;
            }
        }




        #region ILayout 成员
        void ILayout.AdjustSize()
        {
            throw new NotImplementedException();
        }

        void ILayout.AdjustPosition(Rectangle rectArea)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
